import { Space, Button, message, Form, Image, Typography, Row, Col } from 'antd';
import ProCard from '@ant-design/pro-card';
import React, { useState, useRef, useEffect } from 'react';
import { getDvaApp, history, } from 'umi';
import ProForm, {
    ProFormDateRangePicker,
    ProFormSelect,
    ProFormText,
    ProFormTextArea,
} from '@ant-design/pro-form';
import type { ProFormInstance } from '@ant-design/pro-form';
import { PageContainer } from '@ant-design/pro-layout';
import $utils from '@/utils/utils';

import { getPickUpFreeDetail, pickupFreeCreate, pickupFreeUpdate } from '@/services/pickUpWhiteList';
import { findByName } from '@/services/cabinet';
import moment from 'moment';

const { Title } = Typography;

const userInfo = $utils.getStorage('user_info');

const Detail: React.FC = () => {

    // 解决无法调用dispatch
    const dispatch = getDvaApp()._store.dispatch;
    const formRef = useRef<ProFormInstance>();
    const [cur_id, setCur_id] = useState<string>();
    const [pickUpFreeDetail, setPickUpFreeDetail] = useState<any>();

    const [searchValue, setSearchValue] = useState<string>('');
    const [cabinetNames, setCabinetNames] = useState<API.Select[]>([]);

    const l_state: any = history.location.state;
    if (!cur_id && !l_state) {
        history.push('/BusinessConfig/PickUpWhiteList');
    }

    const id: string = l_state?.data?.id || '';
    //  同path更新,只更新state时，通过id重新请求数据
    if ((l_state && id) && (!cur_id || cur_id !== id)) {
        setCur_id(id);
    } else if (l_state && !id && cur_id !== id) {
        setCur_id('');
    }

    const isCreate: boolean = l_state?.status === 'create';
    const isDetail: boolean = l_state?.status === 'detail';
    const isUpdate: boolean = l_state?.status === 'update';

    // 取件白名单详情
    const getPickUpFreeData = async (id: any) => {
        try {
            const msg = await getPickUpFreeDetail({ pickupFreeId: id });;
            if (msg.code === 0) {
                const { startTime, endTime, cabinetIds, ...others } = msg.body;
                const cur_cabinetNames: any = await getCabinetData(others.stationId);
                cabinetIds && setCabinetData(cabinetIds.split(','), cur_cabinetNames);
                setPickUpFreeDetail({ dateRange: [moment(startTime), moment(endTime)], cabinetIds: cabinetIds ? cabinetIds.split(',') : [], ...others });
                return;
            }
        } catch (error) {
            console.log(error);
        }
    };

    // 根据stationId获取柜体列表
    const getCabinetData = async (id: number = userInfo.stationId) => {
        let new_data: API.Select[] = [
            { value: '-1', label: '全部', disabled: false },
        ];
        try {
            const msg = await findByName({ name: '', stationId: id });
            if (msg.code === 0) {
                msg.body.map((item: { id: number, name: string, code: string }) => {
                    new_data.push({
                        label: `${item.name}(${item.code})`,
                        value: `${item.id}`,
                        disabled: false
                    });
                });
                setCabinetNames(new_data);
            }
        } catch (error) {
            console.log(error);
            message.error('柜体列表获取失败!');
        }
        return new_data;
    };

    // 根据柜体列表选择 disable
    const setCabinetData = async (data: any, new_cabinetNames: any[] = [...cabinetNames]) => {
        if (data.length === 0) {
            new_cabinetNames.forEach(item => {
                item.disabled = false;
            })
        }
        else if (+data[0] === -1) {
            new_cabinetNames.forEach(item => {
                if (+item.value !== -1) {
                    item.disabled = true;
                }
                else {
                    item.disabled = false;
                }
            })
        }
        else {
            new_cabinetNames.forEach(item => {
                if (+item.value === -1) {
                    item.disabled = true;
                }
                else {
                    item.disabled = false;
                }
            })
        }
        console.log(data, new_cabinetNames);
        setCabinetNames(new_cabinetNames)
    };

    useEffect(() => {

        if (!cur_id) {
            getCabinetData();
            setPickUpFreeDetail({});
            formRef && formRef.current?.resetFields();
        } else {
            getPickUpFreeData(cur_id);
        }
    }, [cur_id]);

    return (
        <PageContainer>
            {pickUpFreeDetail && <ProCard style={{ marginTop: 8 }} gutter={8} >
                <ProForm
                    labelCol={{ span: 4 }}
                    wrapperCol={{ span: 16 }}
                    layout={"horizontal"}
                    formRef={formRef}
                    initialValues={pickUpFreeDetail}
                    onFinish={async (values) => {
                        let msg = null, { dateRange, cabinetIds, ...others } = values;
                        const params = {
                            name: userInfo.name,
                            cabinetIds: cabinetIds ? cabinetIds.join(',') : '',
                            startTime: dateRange[0],
                            endTime: dateRange[1],
                            stationId: userInfo.stationId,
                            ...others
                        }

                        if (isUpdate) {
                            msg = await pickupFreeUpdate({ pickupFreeId: cur_id, ...params });
                        }
                        else {
                            msg = await pickupFreeCreate(params);
                        }
                        if (msg.code === 0) {
                            message.success('操作成功', 1, () => {
                                // 设置当前tab对象
                                $utils.setNewTab(dispatch, { name: '取件白名单', path: '/BusinessConfig/PickUpWhiteList', isTopMenu: true });
                                history.push('/BusinessConfig/PickUpWhiteList');
                            });
                        }
                    }}
                    submitter={{
                        render: (props, doms) => {
                            return [
                                <Space style={{ marginLeft: '16.66666667%' }}>
                                    {!isDetail && <Button type="primary" htmlType="submit">保存</Button>}
                                    <Button onClick={() => {
                                        // 设置当前tab对象
                                        $utils.setNewTab(dispatch, { name: '取件白名单', path: '/BusinessConfig/PickUpWhiteList', isTopMenu: true });
                                        history.push('/BusinessConfig/PickUpWhiteList');
                                    }}>取消</Button>
                                </Space>
                            ]
                        }
                    }}
                >
                    <ProFormDateRangePicker
                        name="dateRange"
                        label="有效时间"
                        rules={[
                            {
                                required: true,
                            },
                        ]}
                    />
                    <ProFormTextArea
                        width={'md'}
                        name="phone"
                        disabled={!isCreate}
                        label="手机号"
                        rules={[
                            { required: true }
                        ]}
                        placeholder="请输入手机号，如需添加多个，换行输入（回车键）"
                    />
                    <ProFormText
                        width={'md'}
                        name="note"
                        label={'备注'}
                    />
                    <ProFormSelect
                        width={'md'}
                        name="shellFree"
                        label={'是否添加货架白名单'}
                        initialValue={2}
                        fieldProps={{
                            allowClear: false,
                            options: [
                                { value: 1, label: '是' },
                                { value: 2, label: '否' }
                            ],
                        }}
                    />
                    <ProFormSelect
                        width={'lg'}
                        name="cabinetIds"
                        label={'添加柜体白名单'}
                        fieldProps={{
                            mode: 'multiple',
                            showSearch: true,
                            options: cabinetNames,
                            searchValue: searchValue,
                            onSearch: (value: string) => {
                                setSearchValue(value);
                            },
                            onChange: (value: any) => {
                                setSearchValue('')
                                setCabinetData(value)
                            }
                        }}
                    />
                </ProForm>
            </ProCard>}
        </PageContainer>
    );
};

export default Detail;
